local events, shovelButton, _, T = CreateFrame("FRAME"), nil, ...

-- Wait for the player to reach level 85 before initializing the addon
events:RegisterEvent("PLAYER_LOGIN")
events:RegisterEvent("PLAYER_LEVEL_UP")
events:SetScript("OnEvent", function(self, event, level)
	if (event == "PLAYER_LOGIN" and UnitLevel("player") >= 85) or
	   (event == "PLAYER_LEVEL_UP" and level >= 85) then
		self:SetScript("OnEvent", function(self, event, ...) return self[event](self, ...) end)
		self:UnregisterEvent("PLAYER_LEVEL_UP")
		self:RegisterEvent("PLAYER_REGEN_ENABLED")
		self:RegisterEvent("PLAYER_REGEN_DISABLED")
		if not InCombatLockdown() then
			self:RegisterEvent("UPDATE_MOUSEOVER_UNIT")
		end
		shovelButton = CreateFrame("BUTTON", "SpadeActionButton", nil, "SecureActionButtonTemplate")
		shovelButton:SetAttribute("type", "macro")
		shovelButton:SetAttribute("macrotext", "/target mouseover\n/use item:89880")
		T.InitRing()
	end
end)

local afflictionAuras = {[115483] = 80513, [115824] = 79104}
local plants = {} for id in ("0E4C60F6B10F6B90F6CD0F6F80F70E0F71D1017C101AD101C2101D3101DD101F8102211023D1024C1027B1027C1028D"):gmatch(".....") do plants[id] = true end

-- Add a line to the tooltip, if shown
local function addActionHint(tip, text, prefix)
	if tip:IsShown() then
		tip:AddLine((prefix or "") .. (prefix ~= false and "|TInterface\\TUTORIALFRAME\\UI-TUTORIAL-FRAME:::0:0:512:512:0:80:328:412|t: " or "") .. (text or ""))
		tip:Show()
	end
end

-- UPDATE_MOUSEOVER_UNIT does not fire when mouseover disappears, so poll UnitExists and fire it manually
local function watchMouseover(self)
	if not UnitExists("mouseover") then
		self:SetScript("OnUpdate", nil)
		self:GetScript("OnEvent")(self, "UPDATE_MOUSEOVER_UNIT")
	end
end

function events:PLAYER_REGEN_DISABLED()
	self:SetScript("OnUpdate", nil)
	self:UnregisterEvent("UPDATE_MOUSEOVER_UNIT")
	ClearOverrideBindings(self)
	-- No T.UnbindRing() here: ring override bindings automatically cleared in combat
end
function events:PLAYER_REGEN_ENABLED()
	self:RegisterEvent("UPDATE_MOUSEOVER_UNIT")
	self:UPDATE_MOUSEOVER_UNIT()
end
function events:UPDATE_MOUSEOVER_UNIT()
	local guid = UnitGUID("mouseover")
	local npc = guid and (tonumber(guid:sub(5,5),16) % 8 == 3) and guid:sub(6, 10)
	
	-- Check for Tilled Soil, and bind/unbind OPie ring
	local isTilledSoil = npc == "0E4C3" or npc == "0EA56"
	if isTilledSoil and T.BindRing() then
		self:SetScript("OnUpdate", watchMouseover)
		addActionHint(GameTooltip, (T.L"Plant a seed"))
	elseif isTilledSoil then
		addActionHint(GameTooltip, RED_FONT_COLOR_CODE .. (T.L"Requires %s to select seeds"):format(HIGHLIGHT_FONT_COLOR_CODE .. "OPie" .. RED_FONT_COLOR_CODE), false)
	else
		T.UnbindRing()
	end
	
	-- Check for Infested/Parched/Growing crops, and bind the relevant tool
	ClearOverrideBindings(self)
	local toolItem, toolType = (not isTilledSoil) and guid and afflictionAuras[select(11, UnitAura("mouseover", 1))], "PEST"
	toolItem, toolType = toolItem or (plants[npc] and 89880), toolItem and toolType or "SHOVEL"
	toolItem, toolType = toolItem or (npc == "0E4C2" and 89815), toolItem and toolType or "PLOW"
	if toolItem and GetItemCount(toolItem) > 0 then
		self:SetScript("OnUpdate", watchMouseover)
		if toolType == "SHOVEL" then
			SetOverrideBindingClick(self, true, "ALT-BUTTON2", shovelButton:GetName())
		else
			SetOverrideBindingItem(self, true, toolType == "PLOW" and "ALT-BUTTON2" or "BUTTON2", "item:" .. toolItem)
		end
		addActionHint(GameTooltip, T.L["use:" .. toolItem], toolType == "PEST" and "" or "Alt + ")
	elseif toolItem and toolItem ~= 89815 then
		addActionHint(GameTooltip, RED_FONT_COLOR_CODE .. (T.L["tool:" .. toolItem]):gsub("%b[]", HIGHLIGHT_FONT_COLOR_CODE .. "%1" .. RED_FONT_COLOR_CODE), false)
	end
end